package com.hmall.item.config;

import lombok.RequiredArgsConstructor;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.retry.MessageRecoverer;
import org.springframework.amqp.rabbit.retry.RejectAndDontRequeueRecoverer;
import org.springframework.amqp.rabbit.retry.RepublishMessageRecoverer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ErrorMessageConfiguration {

    @Bean
    public DirectExchange directExchange() {
        return new DirectExchange("error.exchange");
    }

    @Bean
    public Queue errorQueue() {
        return new Queue("error.queue");
    }

    @Bean
    public Binding binding(Queue errorQueue, DirectExchange directExchange) {
        return BindingBuilder.bind(errorQueue).to(directExchange).with("error");
    }

    @Bean
    // 注册消费者失败重试达到上限的策略
    public MessageRecoverer messageRecoverer(RabbitTemplate rabbitTemplate) {
        // RejectAndDontRequeueRecoverer 这种模式是重试失败后消费者返回reject，不再接受消息，mq删除消息，但这样可靠性不高

        // 消费者重试失败达到上限后将消息发送给特定的交换机，需要自定义交换机和队列专门收集未能成功处理的消息
        return new RepublishMessageRecoverer(rabbitTemplate, "error.direct", "error");
    }
}
